package cn.demengsite.controller;

import cn.demengsite.base.ProductConfig;
import cn.demengsite.model.BaseInfo;
import cn.demengsite.model.DTO.ImportProductDTO;
import cn.demengsite.model.Product;
import cn.demengsite.model.ProductAttribute;
import cn.demengsite.service.InventoryService;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import tech.ideashare.utils.IS_ExcelUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

@Controller
public class InventoryController {
    private final Logger logger = Logger.getLogger(InventoryController.class.getName());


    @Autowired
    private InventoryService inventoryService;


    @GetMapping("/inventory/showInventoryPage")
    public String showInventoryPage(Model model) {
        HashMap<String ,String > map = new HashMap<>();
        List<ProductAttribute> attributes = new ArrayList<>();
        map = ProductConfig.productNameMap;
        for (String s : map.keySet()) {
            String value  = map.get(s);
            ProductAttribute productAttribute = new ProductAttribute();
            productAttribute.setStyleCode(s);
            productAttribute.setStyleName(value);
            attributes.add(productAttribute);
        }
        model.addAttribute("styleList",attributes);
        logger.info("come in inventory");
        return "inventory";
    }

    @GetMapping("/inventory/getAllProduct")
    @ResponseBody
    public String getAllProduct(@RequestParam(name = "styleCode" ,defaultValue = "0") String styleCode,
                                @RequestParam(name = "getType", required = false) String getType ) {
        BaseInfo productInfo = new BaseInfo();
        if (styleCode.equals("0")) {
            if(getType!=null&&getType.equals("0")){
                productInfo=inventoryService.getAllProductGroupByProductId();
            }else {
                productInfo = inventoryService.getAllProduct();
            }
        }else {
            productInfo = inventoryService.getAllProductByType(styleCode);
        }


        return JSON.toJSONString(productInfo.getObject());
    }

    @PostMapping("/inventory/importProduct")
    @ResponseBody
    public String importProduct(MultipartHttpServletRequest multiReq) {
        String uploadFilePath = multiReq.getFile("file_data").getOriginalFilename();
        List<Product> products = null;
        try {
            InputStream fileIs = multiReq.getFile("file_data").getInputStream();


            products = IS_ExcelUtils.excelToListForXLS(fileIs, Product.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        BaseInfo baseInfo = inventoryService.insertProduct(products);

        System.out.println(uploadFilePath);

        return JSON.toJSONString(products);
    }

    /**
     * 上传图片用的
     * @param productId
     * @param type  0：首图   1：描述图
     * @param multiReq
     * @return
     */
    @PostMapping("/inventory/uploadImage")
    @ResponseBody
    public String uploadImage(
            @RequestParam(required = false) String productId,
            @RequestParam(required = false) int type,
            MultipartHttpServletRequest multiReq) {
        //获取当前的时间戳
        String fullName = multiReq.getFile("file_data").getOriginalFilename();

        String afterName ="."+fullName.split("\\.")[1];

        String timeStamp  = String.valueOf(System.currentTimeMillis());
        String uploadFileName = productId+"_"+timeStamp+afterName;
        try {
            String outputPath= "/home/files/demeng/product"+uploadFileName;
            String attrUrl = "";
            String buketName="light-blue";
            if(type==0){
                //首图
                outputPath="/home/files/demeng/product/main/"+uploadFileName;
                attrUrl="product/main/"+uploadFileName;
                buketName+="/product/main";

            }else if(type==1){
                //描述图
                outputPath="/home/files/demeng/product/desc/"+uploadFileName;
                attrUrl="product/desc/"+uploadFileName;
                buketName+="/product/desc";
            }
            OSSClient ossClient = new OSSClient("oss-cn-beijing.aliyuncs.com","LTAInSgk4S1HKvtC","oB34tutgBlGP01RqGmPc891NitgNZ5");
            byte[] fileIs = multiReq.getFile("file_data").getBytes();
            inventoryService.updateProductImage(productId,type,attrUrl);
            ossClient.putObject("light-blue", attrUrl, new ByteArrayInputStream(fileIs));
            ossClient.shutdown();
//            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputPath));
//            bufferedOutputStream.write(fileIs);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return JSON.toJSONString("");
    }

    @PostMapping("/inventory/updateProduct")
    @ResponseBody
    public String updateProduct(@RequestBody  Product product){

        BaseInfo baseInfo= inventoryService.updateProduct(product);

        return JSON.toJSONString(baseInfo);
    }
    @PostMapping("/inventory/updateProductByProductId")
    @ResponseBody
    public String updateProductByProductId(@RequestBody  Product product){

        BaseInfo baseInfo= inventoryService.updateProductByProductId(product);

        return JSON.toJSONString(baseInfo);
    }

    @PostMapping("/inventory/insertProduct")
    @ResponseBody
    public String insertProduct(@RequestBody ImportProductDTO product){


        List<Product> products = inventoryService.getProducts(product);


        inventoryService.insertProduct(products);
        return JSON.toJSONString(product);
    }


    @GetMapping("/inventory/setSalePrice/{styleCode}/{saleType}")
    @ResponseBody
    public String setSalePrice(@PathVariable int saleType, @PathVariable String styleCode ) {

        BaseInfo baseInfo = new BaseInfo();
        baseInfo = inventoryService.setSalePrice(styleCode,saleType);

        return JSON.toJSONString(baseInfo);
    }

}
